package com.jerry.lastgomall.seckill.service.impl;

import com.alibaba.fastjson.JSON;
import com.jerry.common.to.mq.SeckillOrderTo;
import com.jerry.common.utils.DecimalUtil;
import com.jerry.common.utils.IdWorker;
import com.jerry.common.utils.R;
import com.jerry.lastgomall.seckill.entity.SeckillSessionEntity;
import com.jerry.lastgomall.seckill.feign.ProductFeignService;
import com.jerry.lastgomall.seckill.service.SeckillScheduledService;
import com.jerry.lastgomall.seckill.service.SeckillSessionService;
import com.jerry.lastgomall.seckill.to.SeckillSkuRedisTO;
import com.jerry.lastgomall.seckill.vo.SkuInfoVo;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
public class SeckillScheduledServiceImpl implements SeckillScheduledService {

    @Autowired
    private SeckillSessionService seckillSessionService;
    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    private IdWorker idWorker;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private AmqpTemplate amqpTemplate;

    private final String SESSIONS_CACHE_PREFIX="seckill:sessions:";
    private final String SKUKILL_CHCHE_PREFIX="seckill:skus:";
    private final String SKU_STOCK_SEMAPHONRE="seckill:stock:";    //商品随机码
    private final String SKUKILL_USER="seckill:user:";
    @Override
    public void uploadSeckillSkuLatest3Days() {
        //1.扫描参与秒杀的活动
        List<SeckillSessionEntity> session = seckillSessionService.getLates3DdaySession();
//        System.out.println("session:"+session);
        if (session!=null && session.size()>0){

            //缓存活动信息
            saveSessionSkuInfos(session);
            //缓存活动关联商品信息
            saveSessionInfos(session);
        }
    }

    public void saveSessionInfos(List<SeckillSessionEntity> list){
        System.out.println(list);
        list.stream().forEach(session->{
            long startTime = session.getStartTime().getTime();
            long endTime = session.getEndTime().getTime();
            String kay=SESSIONS_CACHE_PREFIX+startTime+"_"+endTime;
            //缓存活动信息
            Boolean aBoolean = redisTemplate.hasKey(kay);
            if (!aBoolean){
//            List<Long> collect = session.getRelationSkus().stream().map(SeckillSkuRelationEntity::getId).collect(Collectors.toList());
                List<String> collect = session.getRelationSkus().stream().
                        map(item ->item.getPromotionSessionId().toString()+"_"+item.getSkuId().toString()).collect(Collectors.toList());
//                System.out.println("key:"+kay);
//                System.out.println("collect:"+collect);
                redisTemplate.opsForList().leftPushAll(kay,collect);
            }
        });
    }


    public void saveSessionSkuInfos(List<SeckillSessionEntity> list){
        list.stream().forEach(session->{
            BoundHashOperations<String, Object, Object> ops = redisTemplate.boundHashOps(SKUKILL_CHCHE_PREFIX);
            session.getRelationSkus().stream().forEach(seckillSkuVo->{
//                System.out.println("sss"+seckillSkuVo);
                //4.随机码
                long code = idWorker.nextId();

                if(!ops.hasKey(seckillSkuVo.getPromotionSessionId().toString()+"_"+seckillSkuVo.getSkuId().toString())){
                    //缓存商品
                    SeckillSkuRedisTO redisTO = new SeckillSkuRedisTO();
                    //1.sku的基本信息
//                System.out.println("---"+seckillSkuVo.getSkuId());
                    R info = productFeignService.info(seckillSkuVo.getSkuId());
//                System.out.println("++"+info);
                    if (info.get("pmsProduct")!=null){  //成功
                        Map pmsProduct = (Map) info.get("pmsProduct");
                        System.out.println("map:"+pmsProduct);
//                    SkuInfoVo skuInfoVo = redisTO.getSkuInfoVo();
                        SkuInfoVo skuInfoVo = new SkuInfoVo();
                        Object o = pmsProduct.get("productId");
                        Long procuctId=Long.valueOf(String.valueOf(o));
                        System.out.println("procuctId:"+procuctId);
                        skuInfoVo.setProductId(procuctId);
                        skuInfoVo.setProductName((String) pmsProduct.get("productName"));
                        skuInfoVo.setProductTitle((String) pmsProduct.get("productTitle"));
                        skuInfoVo.setProductImg((String) pmsProduct.get("productImg"));
                        skuInfoVo.setProductCon((String) pmsProduct.get("productCon"));
                        Object productPrice = pmsProduct.get("productPrice");
                        BigDecimal bigDecimal = DecimalUtil.toBigDecimal(productPrice);
                        skuInfoVo.setProductPrice(bigDecimal);
                        skuInfoVo.setProductSum((Integer) pmsProduct.get("productSum"));
                        skuInfoVo.setProductStart((String) pmsProduct.get("productStart"));

                        redisTO.setSkuInfoVo(skuInfoVo);
//                    System.out.println("******"+pmsProduct);
                    }
//                SeckillSkuVo pmsProduct = (SeckillSkuVo) info.get("pmsProduct");
//                System.out.println("-------------"+pmsProduct);
                    //2.sku的秒杀信息
                    BeanUtils.copyProperties(seckillSkuVo,redisTO);
                    //3.设置当前秒杀时间信息
                    redisTO.setStartTime(session.getStartTime().getTime());
                    redisTO.setEndTime(session.getEndTime().getTime());


                    redisTO.setRandomCode(code+"");
                    String s = JSON.toJSONString(redisTO);
//                System.out.println("JSON:"+s);
                    ops.put(seckillSkuVo.getPromotionSessionId().toString()+"_"+seckillSkuVo.getSkuId().toString(),s);

                    //如果当前这个场次的商品的库存信息 已经上架
                    //则不需要上架

                    //引入分布式锁的信号量  限流
                    RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHONRE + code+"");
                    //商品可以秒杀的数量(商品库存)作为信号量
                    BigDecimal seckillCount = seckillSkuVo.getSeckillCount();
                    int num = seckillCount.intValue();
                    semaphore.trySetPermits(num);
                }

            });
        });
    }

    @Override
    public void updateTodayProduct() {

    }

    //返回当前时间可以参与的秒杀商品信息
    @Override
    public List<SeckillSkuRedisTO> getCurrentSeckillSkus() {
        //1.确定当前时间属于哪个秒杀场次
        long time = new Date().getTime();
        Set<String> keys = redisTemplate.keys(SESSIONS_CACHE_PREFIX + "*");
        for (String key : keys) {
            //seckill:sessions:1625137101000_1625155200000
            String replace = key.replace(SESSIONS_CACHE_PREFIX, "");
            String[] s = replace.split("_");
            Long start=Long.parseLong(s[0]);
            Long end=Long.parseLong(s[1]);

            if (time>=start && time<=end){
                //2.获取这个秒杀场次需要的所有商品信息
                List<String> range = redisTemplate.opsForList().range(key, -100, 100);
                BoundHashOperations<String, String , String> hsshOps = redisTemplate.boundHashOps(SKUKILL_CHCHE_PREFIX);
                List<String> list = hsshOps.multiGet(range);
                if (!CollectionUtils.isEmpty(list)){
                    List<SeckillSkuRedisTO> collect = list.stream().map(item -> {
//                        SeckillSkuRedisTO redisTO = new SeckillSkuRedisTO();
                        SeckillSkuRedisTO redis = JSON.parseObject((String) item, SeckillSkuRedisTO.class);
                        //秒杀活动开始  不需要返回验证码
                        redis.setRandomCode(null);
                        return redis;
                    }).collect(Collectors.toList());
                    return collect;
                }
                break;
            }
        }
        return null;
    }

    @Override
    public SeckillSkuRedisTO getSkuillInfo(Long skuId) {
        //1.所有参与秒杀商品的key
        BoundHashOperations<String, String, String> ops = redisTemplate.boundHashOps(SKUKILL_CHCHE_PREFIX);
        Set<String> keys = ops.keys();
        if (!CollectionUtils.isEmpty(keys)){
            //5_21
            //正则表达式
            String regx="\\d_"+skuId;
            for (String key : keys) {
                if (Pattern.matches(regx,key)){
                    String json = ops.get(key);
                    SeckillSkuRedisTO redisTO = JSON.parseObject(json, SeckillSkuRedisTO.class);
                    //处理随机码  秒杀时间到了再返回
                    Long startTime = redisTO.getStartTime();
                    Long endTime = redisTO.getEndTime();
                    long nowTime = new Date().getTime();
                    if (nowTime>=startTime && nowTime<=endTime){

                    }else{
                        redisTO.setRandomCode(null);
                    }
                    return redisTO;
                }
            }
        }
        return null;
    }

    @Override
    public String secKill(String killId, String key, Integer num,Long userId) {
        //获取秒杀商品的详细信息
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CHCHE_PREFIX);
        String s = hashOps.get(killId);
        if (StringUtils.isEmpty(s)){
            return null;
        }else{
            SeckillSkuRedisTO redis = JSON.parseObject(s, SeckillSkuRedisTO.class);
            //校验合法性
            //秒杀时间合法性
            Long startTime = redis.getStartTime();
            Long endTime = redis.getEndTime();
            long ttl = endTime - startTime;
            long time = new Date().getTime();
            if (time>=startTime && time<=endTime){
                //随机码和商品ID
                String randomCode = redis.getRandomCode();
                String  skuId =redis.getPromotionSessionId()+"_"+ redis.getSkuId();
                if (randomCode.equals(key) && killId.equals(skuId)){
                    //购物数量是否合理
                    BigDecimal seckillLimit = redis.getSeckillLimit();
                    String s1 = seckillLimit.toString();
                    Integer num1=Integer.parseInt(s1);
                    if (num<=num1){
                        //每个人只能购买一次 只要秒杀成功 ,就去占位 userId_SessionId_skuId
                        String redisKey=SKUKILL_USER+userId+"_"+skuId;
                        // 过期时间 自动过期 当前场次结束
                        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(redisKey, num.toString(), ttl, TimeUnit.MILLISECONDS);
                        if (aBoolean) {
                            //占位成功 从来没有买过
                            RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHONRE + randomCode);

                                boolean b = semaphore.tryAcquire(num);
                                if (b){
                                    //秒杀成功
                                    //快速下单 发送MQ消息
                                    String timeId = com.baomidou.mybatisplus.core.toolkit.IdWorker.getTimeId();
                                    SeckillOrderTo seckillOrderTo = new SeckillOrderTo();
                                    seckillOrderTo.setOrderId(idWorker.nextId());
                                    seckillOrderTo.setUserId(userId);
                                    seckillOrderTo.setNum(num);
                                    seckillOrderTo.setPromotionSessionId(redis.getPromotionSessionId());
                                    seckillOrderTo.setSkuId(skuId);
                                    seckillOrderTo.setSeckillPrice(redis.getSeckillPrice());
                                    rabbitTemplate.convertAndSend("order-event-exchange","order.create.order",seckillOrderTo);
//                                    amqpTemplate.convertAndSend("order.seckill.queue",seckillOrderTo);
                                    return timeId;
                                }
                                return "商品已售完";

                        }else{
                            //占位失败 已经买过了
                            return "只能秒杀一次";
                        }
                    }
                }else{
                    return "库存不足";
                }
            }else{
                return null;
            }
        }
        return null;
    }
}






















